<template>
	<view class="map-box">
		<view class="top-buttons">
			<scroll-view scroll-x="true" class="scroll-view">
				<view class="day-buttons">
					<text :class="{'text-active': selectedCityIndex === -1}" @tap="moveToDay(-1)">概览</text>
					<block v-for="(item, index) in citys" :key="item.id">
						<text :class="{'text-active': selectedCityIndex === index}" @tap="moveToDay(index)">
							{{ item.name }}
						</text>
					</block>
				</view>
			</scroll-view>
		</view>
		<map class="map" id="map" :longitude="longitude" :latitude="latitude" :scale="scale" :polyline="polyline"
			:markers="markers" @markertap="showDescription"></map>
		<view class="description-box" v-if="selectedCityId">
			<MapGoodsCardVue v-if="ID == 1" :id="selectedCityId"></MapGoodsCardVue>
			<MapsencieCardVue v-if="ID == 2" :id="selectedCityId" :ScienceData="selectedScienceData"
				@selectedBack='selectedBack'></MapsencieCardVue>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		getMapData
	} from '@/config/API/Map.js';
	import MapsencieCardVue from './components/MapSencieCard.vue'
	import MapGoodsCardVue from './components/MapGoodsCard.vue';
	import {
		useStore
	} from "../../store/store.js"
	// 引入并初始化腾讯地图 SDK
	const QQMapWX = require('./libs/qqmap-wx-jssdk.js');
	const qqmapsdk = new QQMapWX({
		key: '6QGBZ-QMOLZ-6UXXP-75KGX-F3UG7-DSBHR'
	});

	const selectedCityIndex = ref(-1);
	const selectedCityId = ref(null);

	///选中的景点数据
	const selectedScienceData = ref()
	// 缩放比例 
	const scale = ref(6)
	// 路线坐标数据
	const polyline = ref([]);
	// 设置地图中心点
	const longitude = ref(101);
	const latitude = ref(31.219);
	const mapData = ref([]);

	// 添加选中的标记 ID
	const selectedMarkerId = ref(null);

	// 计算 citys，包含 id 和 name
	const citys = computed(() => {
		return mapData.value.map(item => ({
			id: item.science_id,
			name: item.scienc_name
		}));
	});
	const ID = ref(0)
	// 创建一个映射，以快速查找景点，并根据 scenicIds 筛选并排序景点
	const filterAndSortScenicSpots = (allScenicSpots, scenicIds) => {
		const spotMap = new Map(allScenicSpots.map(spot => [spot.science_id, spot]));
		return scenicIds.filter(id => spotMap.has(id)).map(id => spotMap.get(id));
	};
	// 获取景点数据并处理
	const fetchAndProcessScenicData = async (option) => {
		try {
			const response = await getMapData();
			console.log('API Response:', response); // 打印 API 响应
			const allScenicSpots = response.data;

			if (Array.isArray(allScenicSpots) && allScenicSpots.length > 0) {
				if (option.id == 3 && option.scenicIds) {
					// 解码并分割 scenicIds 参数
					const decodedScenicIds = decodeURIComponent(option.scenicIds);
					const scenicIds = decodedScenicIds.split(',').map(id => id.trim()).filter(id => id !== '').map(
						Number);

					console.log('scenicIds', scenicIds);

					// 验证 scenicIds 是否为非空数组且所有元素都是数字
					if (!Array.isArray(scenicIds) || scenicIds.length === 0 || !scenicIds.every(Number.isFinite)) {
						console.warn('No valid numeric scenicIds received.');
						return;
					}

					console.log('Received and converted scenicIds:', scenicIds);

					// 筛选并排序景点
					const filteredScenicSpots = filterAndSortScenicSpots(allScenicSpots, scenicIds);
					mapData.value = filteredScenicSpots;

					console.log('Filtered and sorted scenic spots:', mapData.value);
				} else {
					mapData.value = allScenicSpots;
					console.log('All scenic spots loaded:', mapData.value);
				}
			} else {
				console.warn('The API returned no valid scenic spots.');
			}
		} catch (error) {
			console.error('获取景点数据失败', error);
			uni.showToast({
				title: '获取景点数据失败，请稍后再试',
				icon: 'none',
				duration: 2000
			});
		}
	};
	// 初始化时将所有点用路线规划连起来
	const planAllRoutes = () => {
		polyline.value = []; // 清除旧的路线
		if (markers.value.length > 1) {
			for (let i = 0; i < markers.value.length - 1; i++) {
				planRoute(markers.value[i], markers.value[i + 1]);
			}
		}
	};
	// 解码腾讯地图 SDK 返回的加密坐标数据
	function decodePolyline(encodedPoints) {
		let kr = 100000;
		let decodedPoints = [];
		let index = 0,
			lat = 0,
			lng = 0;

		while (index < encodedPoints.length) {
			let b, shift = 0,
				result = 0;

			do {
				b = encodedPoints.charCodeAt(index++) - 63;
				result |= (b & 0x1f) << shift;
				shift += 5;
			} while (b >= 0x20);

			let dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
			lat += dlat;

			shift = 0;
			result = 0;

			do {
				b = encodedPoints.charCodeAt(index++) - 63;
				result |= (b & 0x1f) << shift;
				shift += 5;
			} while (b >= 0x20);

			let dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
			lng += dlng;

			decodedPoints.push({
				latitude: lat / kr,
				longitude: lng / kr
			});
		}

		return decodedPoints;
	}
	// 页面加载事件处理
	onLoad(async (option) => {
		console.log('onLoad option:', option); // 打印整个 option 对象

		ID.value = Number(option.id); // 确保 ID 是数字类型

		if (ID.value) {
			try {
				await fetchAndProcessScenicData(option);
				console.log('After fetching data, mapData:', mapData.value); // 打印 mapData 的内容

				if (ID.value === 3 && Array.isArray(mapData.value) && mapData.value.length > 0) {
					// 添加成都作为起点
					const chengdu = {
						science_id: 0, // 起点的 ID
						scienc_name: '成都', // 起点的名称
						latitude: 30.658601, // 成都的纬度
						longitude: 104.064762, // 成都的经度
						scenic_decr: '起点：成都' // 起点的描述
					};
					mapData.value.unshift(chengdu); // 将成都插入到数组的开头
					console.log('Planning routes for markers...');
					planAllRoutes(); // 初始化时规划路线
				} else if (ID.value === 2) {
					// 如果需要对 id=2 进行特定处理，可以在这里添加逻辑
					console.log('Handling case for id=2...');
				} else if (ID.value === 1) {
					// 如果需要对 id=2 进行特定处理，可以在这里添加逻辑
					console.log('Handling case for id=2...');
				}
			} catch (error) {
				console.error('Error fetching and processing scenic data:', error);
			}
		} else {
			console.log('Option id is not 1, 2, or 3. Planning routes for markers...');
			planAllRoutes();
		}
	});

	// 计算 markers
	const markers = computed(() => {
		return mapData.value.map(item => ({
			id: item.science_id,
			latitude: item.latitude,
			longitude: item.longitude,
			width: 15,
			height: 20,
			city: item.scienc_name,
			callout: {
				content: selectedMarkerId.value === item.science_id ? formatContent(item.scenic_decr) : item.scienc_name,
				fontSize: 12,
				borderRadius: 10,
				padding: 8,
				display: 'ALWAYS',
				width: selectedMarkerId.value === item.science_id ? 200 : 100,
				textAlign: 'center',
				bgColor: '#ffffff',
				anchorY: 0
			}
		}));
	});

	// 添加文本格式化函数
	const formatContent = (text) => {
		if (!text) return '';
		// 每20个字符添加一个换行符
		const maxLength = 20;
		let result = '';
		for (let i = 0; i < text.length; i++) {
			result += text[i];
			if ((i + 1) % maxLength === 0) {
				result += '\n';
			}
		}
		return result;
	};

	// 路线规划函数
	const planRoute = (from, to) => {
		qqmapsdk.direction({
			mode: 'driving',
			from: {
				latitude: from.latitude,
				longitude: from.longitude
			},
			to: {
				latitude: to.latitude,
				longitude: to.longitude
			},
			success: (res) => {
				const route = res.result.routes[0].polyline;
				const points = [];
				let kr = 1000000;
				for (let i = 2; i < route.length; i++) {
					route[i] = Number(route[i - 2]) + Number(route[i]) / kr;
				}

				for (let i = 0; i < route.length; i += 2) {
					points.push({
						latitude: route[i],
						longitude: route[i + 1]
					});
				}

				polyline.value.push({
					points: points,
					color: '#00aaffdd', // 设置路线颜色
					width: 4
				});
			},
			fail: (error) => {
				console.error("路线规划失败", error);
			}
		});
	};

	// 切换到指定的景点并重新规划路线
	const moveToDay = (index, selectedId) => {
		if (index === -1) {
			// 选择"概览"
			selectedCityIndex.value = -1;
			selectedCityId.value = null;
			selectedMarkerId.value = null; // 清除选中的标记
			longitude.value = 101;
			latitude.value = 31.219;
			scale.value = 6;
		} else {
			const resData = mapData.value[index];
			console.log('resData==>', resData);
			selectedScienceData.value = resData;
			// 选择城市
			selectedCityIndex.value = index;
			console.log('selectedCityIndex.value', selectedCityIndex.value);
			const marker = markers.value[index];
			if (marker) {
				longitude.value = marker.longitude;
				latitude.value = marker.latitude;
				scale.value = 11;
				// 设置选中的城市 ID
				selectedCityId.value = mapData.value[index].science_id;
				// 设置选中的标记 ID
				selectedMarkerId.value = marker.id;

				// 调用路线规划，仅更新当前点和下一个点的路径
				if (index < markers.value.length - 1) {
					planRoute(marker, markers.value[index + 1], false);
				}
			} else {
				console.log('没有景点id');
			}
		}
	};

	// 显示景点介绍
	const showDescription = (e) => {
		console.log('显示景点介绍');
		const markerId = e.markerId;
		selectedMarkerId.value = markerId; // 设置选中的标记
		
		// 找到对应的marker和索引
		const markerIndex = markers.value.findIndex(m => m.id === markerId);
		if (markerIndex !== -1) {
			// 调用moveToDay来实现相同的效果
			moveToDay(markerIndex);
			selectedCityId.value = markerId;
		}
	};
	const {
		setScienceData
	} = useStore();
	const selectedBack = (ScienceData) => {
		setScienceData(ScienceData);
		// 给状态更新一点时间
		setTimeout(() => {
			uni.navigateBack(); // 返回上一页
		}, 0); // 0ms 或者适当延时
		console.log('ScienceData', ScienceData);
	};
</script>


<style lang="scss" scoped>
	.map-box {
		width: 100%;
		height: 100vh;
		position: relative;

		.top-buttons {
			width: 100%;
			position: fixed;
			top: 13vh;
			left: 0;
			z-index: 9;

			.scroll-view {
				display: flex;
				white-space: nowrap;
				width: 100%;
				padding: 0 20rpx;
				overflow: hidden;
				box-sizing: border-box;

				.day-buttons {
					display: flex;
					gap: 10px;

					text {
						padding: 8px;
						font-size: 26rpx;
						text-align: center;
						border-radius: 5px;
						background-color: #fff;
					}

					.text-active {
						background-color: #000;
						color: white;
					}
				}
			}
		}

		.map {
			width: 100%;
			height: 100vh;
		}

		.description-box {
			width: 100%;
			height: 300rpx;
			// background-color: rgba(255, 255, 255, 1);
			position: fixed;
			bottom: 60rpx;
		}
	}
</style>